package com.v.im.websocketservice.websocket;

import com.v.im.websocketservice.config.WebSocketConfig;
import com.v.im.websocketservice.service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value = "/im",  configurator = WebSocketConfig.class)
@Component
public class ImWebSocket {

    private static ApplicationContext applicationContext;
    public static void setApplicationContext(ApplicationContext context) {
        ImWebSocket.applicationContext = context;
    }

    private WebSocketService webSocketService;

    public Session session;

    public EndpointConfig endpointConfig;




    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        this.session = session;
        this.endpointConfig = config;
        //绑定用户
        webSocketService = applicationContext.getBean(WebSocketService.class);
        webSocketService.bindUserSocket(this);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //解除绑定
        webSocketService.unBindUserSocket(this);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
        //向IM服务器发送消息

        webSocketService.sendImServiceMessage(message);
    }


    @OnError
    public void onError(Session session, Throwable error) {
        //解除绑定
        webSocketService.unBindUserSocket(this);
    }
}
